import { storeToRefs } from 'pinia'
import shopCartStore from '@/piniastore/shopCart'
import { BookInfo } from '@/piniastore/book/state'
import { ShopCart } from '@/piniastore/shopCart/state'
import Books from './index'

export default class ShopCartClass {
  static store = shopCartStore()
  static storeRefs = storeToRefs(ShopCartClass.store)

  static async findShopCartList() {
    await ShopCartClass.store.findShopCartList(1)
    console.log(ShopCartClass.store.getShopCartList)
  }

  static async handleAddBookToShopCart(book: BookInfo) {
    const shopCart: ShopCart = {
      userid: 1,
      checked: false,
      bookisbn: book.ISBN,
      bookname: book.bookname,
      bookpicname: book.bookpicname,
      bookprice: book.originalprice,
      purcharsenum: 1,
    }
    await ShopCartClass.store.addBookToShopCart(shopCart)
    await ShopCartClass.uptBookNumWithSCLstNum(Books.bookList.value)
  }

  static getExistsShopCartID(book: BookInfo) {
    let shopCartList = ShopCartClass.storeRefs.getShopCartList
    const { shopcartid } = shopCartList.value.find((item: ShopCart) => item.bookisbn === book.ISBN)
    return shopcartid
  }

  static async appOrSubtrBookFrmShopCart(type: any, book: BookInfo) {
    const shopCart: ShopCart = {
      userid: 1,
      checked: false,
      bookisbn: book.ISBN,
      bookname: book.bookname,
      shopcartid: ShopCartClass.getExistsShopCartID(book),
      bookpicname: book.bookpicname,
      bookprice: book.originalprice,
      purcharsenum: type === '+' ? ++book.purcharsenum : --book.purcharsenum,
    }
    console.log(shopCart)
    
    await ShopCartClass.store.appOrSubtrBookFrmShopCart(shopCart)
  }

  static uptBookNumWithSCLstNum(bookList: BookInfo[]) {
    const shopCartList = ShopCartClass.store.getShopCartList
    if (shopCartList) {
      shopCartList.forEach((shopCart: ShopCart) => {
        bookList.forEach((book) => {
          if (shopCart.bookisbn === book.ISBN) {
            book.purcharsenum = shopCart.purcharsenum
            console.log(book.bookname, shopCart.purcharsenum)
          }
        })
      })
    }
  }
}
